import React, {useEffect, useState } from "react";
import {useLocation, useNavigate } from "react-router-dom";
import axios from "axios";
import moment from 'moment';
import {Descriptions, PageHeader} from 'antd';
import { HeartTwoTone } from '@ant-design/icons'

export default function Detail() {
    const [newsData, setNewsData]= useState({});
    const location= useLocation();
    const navigate= useNavigate();
    const id= location.pathname.split('/')[2];
    useEffect(()=>{
        axios.get(`/api/news/${id}?_expand=category&_expand=role`).then(response=>{
            const data= response.data;
            setNewsData({
                ...data,
                view: data.view + 1
            });
            return data;
        }).then(res=>{
            axios.patch(`/api/news/${id}`, {
                view: res.view + 1
            });
        }).catch((err)=>{
            navigate('/nofound', {replace: true});
        })
    }, [id]);

    const handleStar= ()=>{
        setNewsData({
            ...newsData,
            star: newsData.star + 1
        });
        axios.patch(`/api/news/${id}`, {
            star: newsData.star + 1
        });
    }

    return (
        <div style={{padding:"20px"}}>
            <PageHeader
                onBack={() => navigate(-1)}
                title={newsData.title}
                subTitle={
                    <div>
                        <span style={{marginRight: "10px"}}>{newsData.category?.title}</span>
                        <HeartTwoTone twoToneColor="#eb2f96" onClick={handleStar}/>
                    </div>
                }
            >
                <Descriptions size="small" column={3}>
                    <Descriptions.Item label="创建者">{newsData.author}</Descriptions.Item>
                    <Descriptions.Item label="发布时间">{newsData.publishTime ? moment(newsData.publishTime).format('YYYY-MM-DD HH:mm:ss') : '-'}</Descriptions.Item>
                    <Descriptions.Item label="区域">{newsData.region}</Descriptions.Item>
                    <Descriptions.Item label="访问数量">{newsData.view}</Descriptions.Item>
                    <Descriptions.Item label="点赞数量">{newsData.star}</Descriptions.Item>
                    <Descriptions.Item label="评论数量">{newsData.comment || 0}</Descriptions.Item>
                </Descriptions>
            </PageHeader>

            <div dangerouslySetInnerHTML={{__html:newsData.content}} style={{padding:'10px 24px', border: '1px dashed gray', minHeight: '200px'}}></div>
        </div>
    )
}
